package com.xhapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xhapi.pojo.entity.Text;
import com.xhapi.pojo.vo.TextCorrectionVO;
import com.xhapi.service.TextService;
import com.xhapi.utils.textCorrectionUtils.WebTextCorrection;
import com.xhapi.utils.textRewritingUtils.TextRewriting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

import static com.xhapi.utils.textCorrectionUtils.WebTextCorrection.doPostJson;
import static com.xhapi.utils.textCorrectionUtils.WebTextCorrection.gson;

@Service
@Slf4j
public class TextServiceImpl implements TextService {
    @Autowired
    TextRewriting textRewriting;
    @Override
    public TextCorrectionVO correctText(Text text) throws Exception {
        WebTextCorrection webTextCorrection = new WebTextCorrection();
        String url = webTextCorrection.getAuthUrl("https://api.xf-yun.com/v1/private/s9a87e3ec", "889e0b5155405f467a3b0d440152fe20", "NmM2Mjk4MTg4MDc5MjEzYmI3MzAzNmQ1");
        String json = webTextCorrection.getRequestJson("d8f23a13", text.getText());
        String backResult = doPostJson(url, json);
        log.info("文本纠错返回结果：{}", backResult);
        WebTextCorrection.JsonParse jsonParse = gson.fromJson(backResult, WebTextCorrection.JsonParse.class);
        String base64Decode = new String(Base64.getDecoder().decode(jsonParse.payload.result.text), StandardCharsets.UTF_8);

        ObjectMapper mapper=new ObjectMapper();
        TextCorrectionVO textCorrectionVO;
        textCorrectionVO=mapper.readValue(base64Decode,TextCorrectionVO.class);
        System.out.println("text字段base64解码后纠错信息：" + base64Decode);
        return textCorrectionVO;
    }

    /*
    * // 改写等级 <L1>  ~  <L6>  等级越高，改写程度越深
    private String LEVEL="<L6>";
    * */
    @Override
    public String rewriteText(Text text) {
        try {
            String resp = textRewriting.doRequest(text.getText(),text.getLevel());
            JSONObject tempJSONObject= JSON.parseObject(resp);
            TextRewriting.JsonParse myJsonParse = gson.fromJson(resp, TextRewriting.JsonParse.class);
            String textBase64Decode=new String(Base64.getDecoder().decode(myJsonParse.payload.result.text), StandardCharsets.UTF_8);
            // 返回改写后的文本，和改写文本对应的位置信息
            JSONArray jsonArray=JSONArray.parseArray(textBase64Decode);
            JSONArray innerArray=jsonArray.getJSONArray(0);
            return innerArray.getString(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
